﻿using AutoMapper;
using B.S.Packaged.Domain;
using B.S.Packaged.Domain.Tree;
using B.S.Packaged.ErrorCode;
using B.S.Packaged.WebAPI.Write.Applications.Commands.ProductionLine;
using MediatR;
using SqlSugar;

namespace B.S.Packaged.WebAPI.Write.Applications.CommandHandlers
{
    public class AddProductionLineHander : IRequestHandler<AddProductionLineCommand, APIResult<int>>
    {

        private readonly IMapper mapper;
        private readonly ISqlSugarClient db;

        public AddProductionLineHander(IMapper mapper, ISqlSugarClient db)
        {
            this.mapper = mapper;
            this.db = db;
        }

        /// <summary>
        /// 添加产线
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<APIResult<int>> Handle(AddProductionLineCommand request, CancellationToken cancellationToken)
        {
            APIResult<int> result = new APIResult<int>();
            var entity = mapper.Map<Domain.Tree.ProductionLine>(request);
            var one = db.Queryable<Domain.Tree.ProductionLine>().Where(x => x.ProductionLineName == request.ProductionLineName).First();

            if (one != null)
            {
                result.code = APIResultCode.noname;
                result.msg = APIResultCode.noname.ToString();
                result.data = 0;
                return await Task.FromResult(result);
            }

            var list = await db.Insertable<Domain.Tree.ProductionLine>(entity).ExecuteCommandAsync();

            if (list > 0)
            {
                result.code = APIResultCode.success;
                result.msg = APIResultCode.success.ToString();
                result.data = list;
            }
            else
            {
                result.code = APIResultCode.failed;
                result.msg = APIResultCode.failed.ToString();
                result.data = list;
            }

            return await Task.FromResult(result);
        }
    }
}
